<?php
namespace app\common;
use think\db;
use app\common\Eldata;

class Mdatatoe
{
    protected $es=null;

    public function __construct()
    {
        $this->es = new Eldata();
    }

    public function MysqlToElastic($table,$count,$indexName,$indexType,$indexID) //$indexBody
    {
        $selected_data = Db::table($table)->limit($count)->select();
        if($selected_data == null){
            return false;
        }
        $transform_data=array();
        foreach($selected_data as $data){
            $data_keys=array_keys($data);
            foreach($data_keys as $dk){
                $transform_data[$dk] = $data[$dk];
            }
        }

        if(is_empty($trasnform_data)){
            return false;
        }
        return $this->es->insertDoc($indexName, $indexType, $indexID, $trasnform_data);
    }

    public function ElasticToMysql($indexName, $indexType, $table)
    {
        $search_datas=$this->es->searchIndex($indexName, $indexType, new \stdClass());

        $search_datas=json_decode($search_datas);
        $insert_data=array();
        foreach($search_datas['hits']['hits'] as $sd) {
            $sd_keys = array_keys($sd);
            $tmp_datas=array();
            foreach($sd_keys as $sd_key){
                $tmp_datas[$sd_key] = $sd[$sd_key];
            }
            array_push($insert_data,$tmp_datas);
        }
        $ok = Db::table($table)->insert($insert_data);
        if($ok){
            return true;
        }else{
            return false;
        }
    }

    public function ElasticToMysqlDoc($indexName, $indexType, $indexID, $table)
    {
        $get_data = $this->es->getDoc($indexName, $indexType, $indexID);

        $get_data = json_decode($get_data);
        $insert_data = array();
        foreach(array_keys($get_data['_source']) as $gd_key)
        {
            $insert_data[$gd_key] = $get_data['_source'][$gd_key];
        }

        $ok = Db::table($table)->insert($insert_data);

        return $ok ? true : false;
    }
}
